package deployment

import (
	"krm-backend/config"
	"krm-backend/controllers"
	"krm-backend/utils/logs"
	"time"

	"github.com/dotbalo/kubeutils/kubeutils"
	"github.com/gin-gonic/gin"
	appsv1 "k8s.io/api/apps/v1"
)

func Restart(r *gin.Context) {
	logs.Debug(nil, "重启deployment")
	var deployment appsv1.Deployment
	var info controllers.Info
	info.Item = &deployment
	kubeconfig := controllers.NewInfo(r, &info, "重启成功")
	//改为接口形式的创建
	var kubeUtilser kubeutils.KubeUtilser
	instance := kubeutils.NewDeployment(kubeconfig, &deployment)
	originSts, err := instance.Get(info.Namespace, info.Name)
	if err != nil {
		info.ReturnData.Message = "未找到该资源"
		info.ReturnData.Status = 400
		r.JSON(200, info.ReturnData)
		return
	}

	sts, ok := originSts.(*appsv1.Deployment)
	if !ok {
		info.ReturnData.Message = "类型断言失败"
		info.ReturnData.Status = 500
		r.JSON(200, info.ReturnData)
		return
	}
	newSts := sts.DeepCopy()
	if newSts.Spec.Template.Annotations == nil {
		newSts.Spec.Template.Annotations = make(map[string]string)
	}
	newSts.Spec.Template.Annotations["kubeasy.com/restartedAt"] = time.Now().Format(config.TimeFormat)

	// 显式设置 Name 和 Namespace（防止为空）
	newSts.Name = info.Name
	newSts.Namespace = info.Namespace

	// 替换 instance.Item 为新对象
	instance.Item = newSts

	logs.Debug(map[string]interface{}{
		"item_name":      instance.Item.Name,
		"item_namespace": instance.Item.Namespace,
	}, "准备 Update 的 Item")
	// instance.Item
	// if instance.Item.Spec.Template.Annotations == nil {
	// 	instance.Item.Spec.Template.Annotations = make(map[string]string)
	// }
	// deployment = *instance.Item
	// deployment.Spec.Template.Annotations["kubeasy.com/restartedAt"] = time.Now().Format(config.TimeFormat)
	//把实例复制给kubeUtilser
	kubeUtilser = instance
	//使用kubeUtilser创建资源
	// kubeUtilser.Create("default")
	info.Update(r, kubeUtilser)

}
